/*
    Copyright is LuoYuShun to 2022-2022
*/
package cn.com.laya.service.fourdemo.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 描述
 *
 * @author LuoYuShun
 * @since 2022-11-24
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {
    /**
     * spring的上下文
     */
    private static volatile ApplicationContext applicationContext;

    /**
     * 设置上下文
     *
     * @param applicationContext 应用的上下文
     * @throws BeansException 异常
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringContextUtils.applicationContext == null) {
            synchronized(SpringContextUtils.class) {
                if (SpringContextUtils.applicationContext == null) {
                    SpringContextUtils.applicationContext = applicationContext;
                }
            }
        }

    }

    public static <T> T getBean(Class<T> classType) {
        checkApplicationContext();
        return applicationContext.getBean(classType);
    }

    public static void checkApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
        }
    }
}
